/**
 * 
 */
package com.kingbi.util.dao.hibernate;

import java.io.ByteArrayInputStream;
import java.sql.SQLException;
import java.util.Properties;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.dialect.Dialect;
import org.hibernate.tool.hbm2ddl.DatabaseMetadata;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
 * @author mouzb
 *
 */
public class NativeSqlHelper extends HibernateDaoSupport {
	private Properties props;
	
	public Properties getProps() {
		return props;
	}

	public void setProps(Properties props) {
		this.props = props;
	}
	public void execute(final String sql){
		this.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException {
				session.createSQLQuery(sql).executeUpdate();
				return null;
			}
		});
	}
	public String[] generateUpdateSql(final String mapXml){
		return (String[])this.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException {
				try {
					ByteArrayInputStream input=new ByteArrayInputStream(mapXml.getBytes());
					Configuration cfg=new Configuration();
					cfg.addProperties(props);
					cfg.addInputStream(input);
					Dialect dialect=Dialect.getDialect(props);
					DatabaseMetadata meta;
					meta = new DatabaseMetadata(session.connection(),dialect);
					return cfg.generateSchemaUpdateScript(dialect,meta);
				} catch (SQLException e) {
					e.printStackTrace();
					throw new HibernateException(e);
				}
			}
		});
		
	}
	public String[] generateDropSql(final String mapXml){
		return (String[])this.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException {
				ByteArrayInputStream input=new ByteArrayInputStream(mapXml.getBytes());
				Configuration cfg=new Configuration();
				cfg.addProperties(props);
				cfg.addInputStream(input);
				Dialect dialect=Dialect.getDialect(props);
				//DatabaseMetadata meta;
				//meta = new DatabaseMetadata(session.connection(),dialect);
				return cfg.generateDropSchemaScript(dialect);
			}
		});
		
	}
}
